package com.chinasoft.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 添加过滤器，解决跨域访问
 */


public class MyFilter implements Filter {


    private static final Logger logger = LoggerFactory.getLogger(MyFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
        // 将ServletResponse转换为HttpServletResponse
        HttpServletResponse httpResponse = (HttpServletResponse) res;
        HttpServletRequest request=(HttpServletRequest)req;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setContentType("application/json;charset=UTF-8");
        httpResponse.setHeader("Access-Control-Allow-Methods", "*");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,token,access-control-allow-origin,Content-disposition,X-Requested-With");
        // 如果要把Cookie发到服务器，需要指定Access-Control-Allow-Credentials字段为true
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Expose-Headers", "*");


        String method = request.getMethod();
        if (method.equalsIgnoreCase("OPTIONS")){
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        try {
            chain.doFilter(req, res);
        } catch (Exception e) {
            logger.error("",e);
        }
    }

    @Override
    public void destroy() {

    }
}
